package com.example.pt.controller;

import com.example.pt.dto.ApiResponse;
import com.example.pt.entity.User;
import com.example.pt.repository.UserRepository;
import com.example.pt.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/admin")
public class AdminController {

    private final UserService userService;
    @Autowired
    private UserRepository userRepository;

    public AdminController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/cleanup")
    public String cleanupLowRatioUsers() {
        int deleted = userService.deleteUsersWithLowRatio();
        return "已删除分享率低于 0.5 的用户数量: " + deleted;
    }

    @DeleteMapping("/cleanInactiveUsers")
    public ApiResponse<List<String>> cleanInactiveUsers() {
        LocalDate sixMonthsAgo = LocalDate.now().minusMonths(6);
        List<User> allUsers = userRepository.findAll();
        List<String> deletedUsernames = new ArrayList<>();

        for (User user : allUsers) {
            LocalDate lastLogin = user.getLast_login();

            if (lastLogin == null || lastLogin.isBefore(sixMonthsAgo)) {
                deletedUsernames.add(user.getUsername());
                userRepository.delete(user);
            }
        }

        return ApiResponse.success(deletedUsernames);
    }
}

